package cn.edu.zut.project1.service.Impl;

import cn.edu.zut.project1.mapper.MessageMapper;
import cn.edu.zut.project1.mapper.OrdersMapper;
import cn.edu.zut.project1.pojo.Message;
import cn.edu.zut.project1.pojo.Orders;
import cn.edu.zut.project1.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public void sendSystemMsg(Integer sellerOrBuyerId, String orderNo, String content) {
        Orders orders = ordersMapper.selectByOrderNo(orderNo);

        // 1. 建议信息是否允许发送(系统自动发送)
        if(orders == null){
            throw new RuntimeException("订单不存在，无法发提醒");
        }

        if(!(orders.getSellerId().equals(sellerOrBuyerId)||orders.getBuyerId().equals(sellerOrBuyerId))){
            throw new RuntimeException("该用户与订单无关，不能发送");
        }

        // 2. 构建系统消息（senderId=0，type=0）
        Message msg = new Message();
        msg.setSenderId(0);          // 0代表系统
        msg.setReceiverId(sellerOrBuyerId);
        msg.setOrderNo(orderNo);
        msg.setContent(content);
        msg.setType(0);             // 0=系统消息
        msg.setIsRead(0);           // 默认为未读
        msg.setCreateTime(LocalDateTime.now());

        // 3. 存入数据库
        messageMapper.insert(msg);



    }

    @Override
    public void sendUserMsg(Integer senderId, Integer receiverId, String orderNo, String content) {
        // 1. 校验订单存在
        Orders order = ordersMapper.selectByOrderNo(orderNo);
        if (order == null) {
            throw new RuntimeException("订单不存在，不能发消息");
        }

        // 2. 校验发送者和接收者：必须是订单的买家和卖家（避免陌生人骚扰）
        boolean isBuyerAndSeller = (order.getBuyerId().equals(senderId) && order.getSellerId().equals(receiverId))
                || (order.getSellerId().equals(senderId) && order.getBuyerId().equals(receiverId));
        if (!isBuyerAndSeller) {
            throw new RuntimeException("只能给订单相关的买家/卖家发消息");
        }

        // 3. 构建用户消息（senderId=当前用户，type=1）
        Message msg = new Message();
        msg.setSenderId(senderId);    // 发送者是当前用户
        msg.setReceiverId(receiverId);
        msg.setOrderNo(orderNo);
        msg.setContent(content);
        msg.setType(1);               // 1=用户消息
        msg.setIsRead(0);
        msg.setCreateTime(LocalDateTime.now());

        // 4. 存入数据库
        messageMapper.insert(msg);
    }

    @Override
    public List<Message> getOrderMsgs(String orderNo, Integer userId) {
        // 校验用户和订单有关联（避免查他人订单消息）
        Orders order = ordersMapper.selectByOrderNo(orderNo);
        if (!order.getBuyerId().equals(userId) && !order.getSellerId().equals(userId)) {
            throw new RuntimeException("无权查看该订单消息");
        }

        // 查该订单的所有消息（按时间倒序，最新的在前面）
        return messageMapper.selectByOrderNo(orderNo);
    }


}
